package simulation;

import gnu.cajo.utils.extra.TransparentItemProxy;
import gui.BackgroundPanel;
import gui.GUI;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import combat.protocol.interfaces.TeamInt;
import combat.protocol.interfaces.UserInt;
import combat.protocol.interfaces.VehicleInt;
import lookandfeel.colorScheme;
import lookandfeel.customButton;

public class teamSelection extends JFrame implements Runnable{

    private static Thread _runner;

	private static final long serialVersionUID = 1L;

	private JPanel container = new BackgroundPanel("./images/teamselect/team_select_bg.png");
	
	//Default spectator
	private static int selectedTeamID = 2;
    
	private static ArrayList<VehicleInt> _frigates = new ArrayList<VehicleInt>();
	private static ArrayList<VehicleInt> _submarines = new ArrayList<VehicleInt>();
	
	//Define images
	private ImageIcon _spectatorImgEnter =  new ImageIcon("./images/teamselect/spectators_selected.png");
	private ImageIcon _spectatorImgExit = new ImageIcon("./images/teamselect/spectators_unselected.png");
	private ImageIcon _attackImgEnter =  new ImageIcon("./images/teamselect/attack_selected.png");
	private ImageIcon _attackImgExit = new ImageIcon("./images/teamselect/attack_unselected.png");
	private ImageIcon _defenseImgEnter =  new ImageIcon("./images/teamselect/defense_selected.png");
	private ImageIcon _defenseImgExit = new ImageIcon("./images/teamselect/defense_unselected.png");
	private ImageIcon _frigateImgEnter =  new ImageIcon("./images/teamselect/frigate_selected.png");
	private ImageIcon _frigateImgExit = new ImageIcon("./images/teamselect/frigate_unselected.png");
	private ImageIcon _submarineImgEnter =  new ImageIcon("./images/teamselect/submarine_selected.png");
	private ImageIcon _submarineImgExit = new ImageIcon("./images/teamselect/submarine_unselected.png");
	
	private JButton btnSpectators;
	private JButton btnAttackers;
	private JButton btnDefenders;
	private static JButton btnFrigate;
	private static JButton btnSubmarine;
	private customButton btnCancel;
	private customButton btnJoin;
	
	private String selectedVehicle = "";
	
	private String strButtonHighlight = "";

	private static int countFrigatesUsed = 0;
	private static int countSubmarinesUsed = 0;
	
	private boolean attackersMouseListActive = true;
	private boolean defendersMouseListActive = true;
	
	public void switchTeam()
	{
		// Switch to selected team
		Connection.simulation.switchTeam_Remote(
				(UserInt) TransparentItemProxy.getItem(Connection.getMe(), new Class[] { UserInt.class }), 
				(TeamInt) TransparentItemProxy.getItem(Connection.simulation.getTeams_Remote().get(selectedTeamID), new Class[] { TeamInt.class })
		);
	}

	public void setSelectedVehicle(String _vehicle){
			btnJoin.setEnabled(true);
			selectedVehicle = _vehicle;
		}
	
	public String getSelectedVehicle(){
			return selectedVehicle;
		}
	
	public teamSelection(JFrame StartUp_Frame)
	{
		StartUp_Frame.dispose();
		_runner = new Thread(this,"Data Thread");
    	_runner.start();
		
		new colorScheme();
		
		// Initialize
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle(Config.appTitle);
		this.getContentPane().add(container);
		this.setPreferredSize(new Dimension(480, 400));
		this.setUndecorated(true);
		this.setVisible(true);
		this.setAlwaysOnTop(true);
		this.setResizable(false);
		
		// Get the size of the screen
	    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
	    
	    // Determine the new location of the window
	    int w = this.getPreferredSize().width;
	    int h = this.getPreferredSize().height;
	    int x = (dim.width-w)/2;
	    int y = (dim.height-h)/2;
	    
	    // Move the window
	    this.setLocation(x, y);
		
		// Everything is as normal
		
	    /***********START action listeners************/
		//Create actionlisteners click events
		class spectatorsOnClick implements ActionListener{
			public void actionPerformed(ActionEvent e) {
				//Disable the boat buttons
				btnFrigate.setEnabled(false);
				btnSubmarine.setEnabled(false);
				//Enable the join button
				btnJoin.setEnabled(true);
				
				//Set button highlight
				strButtonHighlight = "Spectators";
				
				selectedTeamID = 2;
				
				//Set selected vehicle null
				selectedVehicle = "";
				
				//Set selected team to 2 :: Spectators
				switchTeam();
		
				btnSpectators.setIcon(_spectatorImgEnter);
				btnAttackers.setIcon(_attackImgExit);
				btnDefenders.setIcon(_defenseImgExit);
			}
		}
		class attackersOnClick implements ActionListener{
			public void actionPerformed(ActionEvent e) {
				if(attackersMouseListActive){
					btnFrigate.setEnabled(true);
					btnSubmarine.setEnabled(true);
					
					selectedTeamID = 1;
					//Set selected team to 1 :: Attackers
					switchTeam();
					
					//Set button highlight
					strButtonHighlight = "Attackers";
					
					btnAttackers.setIcon(_attackImgEnter);
					btnSpectators.setIcon(_spectatorImgExit);
					btnDefenders.setIcon(_defenseImgExit);
				}
			}
		}
		class defendersOnClick implements ActionListener{
				public void actionPerformed(ActionEvent e) {
					if(defendersMouseListActive){
						btnFrigate.setEnabled(true);
						btnSubmarine.setEnabled(true);
						
						selectedTeamID = 0;
						//Set selected team to 0 :: Defenders
						switchTeam();
						
						//Set button highlight
						strButtonHighlight = "Defenders";
						
						btnDefenders.setIcon(_defenseImgEnter);
						btnSpectators.setIcon(_spectatorImgExit);
						btnAttackers.setIcon(_attackImgExit);
					}
				}
			}
		class frigateOnClick implements ActionListener{
			public void actionPerformed(ActionEvent e) {
				setSelectedVehicle("FRIGATE");
				btnFrigate.setIcon(_frigateImgEnter);
				btnSubmarine.setIcon(_submarineImgExit);
			}
		}
		class submarineOnClick implements ActionListener{
			public void actionPerformed(ActionEvent e) {
				setSelectedVehicle("SUBMARINE");
				btnSubmarine.setIcon(_submarineImgEnter);
				btnFrigate.setIcon(_frigateImgExit);
			}
		}
		
		//Create mouseadapters hover effects
		class spectatorsHover extends MouseAdapter{
			public void mouseEntered(MouseEvent e){
				if(strButtonHighlight != "Spectators"){
					btnSpectators.setIcon(_spectatorImgEnter);
				}
			}
			public void mouseExited(MouseEvent e){
				if(strButtonHighlight != "Spectators"){
					btnSpectators.setIcon(_spectatorImgExit);
				}
			}
		}
		class attackersHover extends MouseAdapter{
			public void mouseEntered(MouseEvent e){
				if(attackersMouseListActive){
					if(strButtonHighlight != "Attackers"){
						btnAttackers.setIcon(_attackImgEnter);
					}
				}
			}
			public void mouseExited(MouseEvent e){
				if(attackersMouseListActive)
				{
					if(strButtonHighlight != "Attackers"){
						btnAttackers.setIcon(_attackImgExit);
					}
				}
			}
		}
		class defendersHover extends MouseAdapter{
			public void mouseEntered(MouseEvent e){
				if(defendersMouseListActive){
					if(strButtonHighlight != "Defenders"){
						btnDefenders.setIcon(_defenseImgEnter);
					}
				}
			}
			public void mouseExited(MouseEvent e){
				if(defendersMouseListActive){
					if(strButtonHighlight != "Defenders"){
						btnDefenders.setIcon(_defenseImgExit);
					}
				}
			}
		}
		class frigateHover extends MouseAdapter{
			public void mouseEntered(MouseEvent e){
				if(selectedVehicle != "FRIGATE"){
					btnFrigate.setIcon(_frigateImgEnter);
				}
			}
			public void mouseExited(MouseEvent e){
				if(selectedVehicle != "FRIGATE"){
					btnFrigate.setIcon(_frigateImgExit);
				}
			}
		}
		class submarineHover extends MouseAdapter{
			public void mouseEntered(MouseEvent e){
				if(selectedVehicle != "SUBMARINE"){
					btnSubmarine.setIcon(_submarineImgEnter);
				}
			}
			public void mouseExited(MouseEvent e){
				if(selectedVehicle != "SUBMARINE"){
					btnSubmarine.setIcon(_submarineImgExit);
				}
			}
		}
		/***********END action listeners************/
		
		/***********START team select************/
		JPanel pnlTeamSelect = new JPanel();
		pnlTeamSelect.setBorder(BorderFactory.createEmptyBorder(30, 0, 25, 0));
		pnlTeamSelect.setSize(this.getWidth(), 150);
		pnlTeamSelect.setOpaque(false);
		
		// Button Team Attackers
		btnAttackers = new JButton(_attackImgExit);
		btnAttackers.setSize(new Dimension(115,130));
		btnAttackers.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
		btnAttackers.addActionListener(new attackersOnClick());
		btnAttackers.addMouseListener(new attackersHover());
		
		// Button Team Defenders
		btnDefenders = new JButton(_defenseImgExit);
		btnDefenders.setSize(new Dimension(115,130));
		btnDefenders.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
		btnDefenders.addActionListener(new defendersOnClick());
		btnDefenders.addMouseListener(new defendersHover());
		
		// Button Team Spectators
		btnSpectators = new JButton(_spectatorImgExit);
		btnSpectators.setSize(new Dimension(115, 130));
		btnSpectators.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
		btnSpectators.addActionListener(new spectatorsOnClick());
		btnSpectators.addMouseListener(new spectatorsHover());
		
		pnlTeamSelect.add(btnAttackers);

		try {
			BufferedImage imgArrows = ImageIO.read(new File("./images/teamselect/arrows.png"));
			pnlTeamSelect.add(new JLabel(new ImageIcon(imgArrows)));
		} catch (IOException e) {
		}
		pnlTeamSelect.add(btnDefenders);
		try {
			BufferedImage imgArrows = ImageIO.read(new File("./images/teamselect/arrows.png"));
			pnlTeamSelect.add(new JLabel(new ImageIcon(imgArrows)));
		} catch (IOException e) {
		}
		pnlTeamSelect.add(btnSpectators);
		/***********END team select************/
		
		/***********START vehicle select************/
		JPanel pnlVehicleSelect = new JPanel();
		pnlVehicleSelect.setSize(this.getWidth(), 200);
		pnlVehicleSelect.setOpaque(false);
		
		// Button Frigate
		btnFrigate = new JButton(_frigateImgExit);
		btnFrigate.setSize(new Dimension(324,58));
		btnFrigate.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
		btnFrigate.addActionListener(new frigateOnClick());
		btnFrigate.addMouseListener(new frigateHover());
		
		// Button Submarine
		btnSubmarine = new JButton(_submarineImgExit);
		btnSubmarine.setSize(new Dimension(324,58));
		btnSubmarine.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
		btnSubmarine.addActionListener(new submarineOnClick());
		btnSubmarine.addMouseListener(new submarineHover());
		pnlVehicleSelect.setLayout(new GridLayout(2, 0, 0, 10));
		btnFrigate.setEnabled(false);
		btnSubmarine.setEnabled(false);
		pnlVehicleSelect.add(btnFrigate);
		pnlVehicleSelect.add(btnSubmarine);
		/***********END vehicle select************/
		
		/******START submit buttons ********/
		JPanel pnlButtons = new JPanel();
		pnlButtons.setOpaque(false);
		btnCancel = new customButton("Cancel");
			btnCancel.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					Connection.getMyTeam().removeUser(Connection.getMe());
					System.exit(1);
				}
			});
			
		btnJoin = new customButton("Join");
		final JFrame _self = this;
			btnJoin.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					// Set team and vehicle to user!
					// Loop through the submarines and frigates to check if they are locked
					if(getSelectedVehicle().equals("FRIGATE"))
					{
						for(int k = 0; k < _frigates.size(); k++)
						{
							boolean locked = (boolean) _frigates.get(k).getLocked();
							if(!locked)
							{
								Connection.getMe().setUserVehicle(Data.getVehiclesByTeam(Connection.getMyTeam()).get(k));
								Connection.getMyVehicle().setLocked(true);
								break;
							}
						}
					}
					else if(getSelectedVehicle().equals("SUBMARINE"))
					{
						for(int k = 0; k < _submarines.size(); k++)
			 			{
			  				 boolean locked = (boolean) _submarines.get(k).getLocked();
			  				 if(!locked)
			  				 {
			  					Connection.getMe().setUserVehicle(Data.getVehiclesByTeam(Connection.getMyTeam()).get(2));
								Connection.getMyVehicle().setLocked(true);
								break;
			  				 }
			  			}
					}
					
					if((Connection.getMyTeam() != null) && (Connection.getMyVehicle() != null))
					{
						System.out.println(Connection.getMe().getUserName() + " has joined team '" + Connection.getMyTeam().getTeamName() + "' and has vehicle '" + Connection.getMyVehicle().getName() + "'.");
						_runner.stop();
						new GUI(_self);
					}
				}
			});			
		
		btnJoin.setEnabled(false);
		
		// Add Cancel & Join button to panel
		pnlButtons.add(btnCancel);
		pnlButtons.add(btnJoin);
		pnlButtons.setBorder(BorderFactory.createEmptyBorder(10,20,0,0));
		/*****END submit buttons *****/

		// Add all panels to a container
		container.add(pnlTeamSelect);
		container.add(pnlVehicleSelect);
		container.add(pnlButtons);

		this.pack();
	}
	
	public static void updateButtons()
	{		
		// Disable some buttons
		if(selectedTeamID == 0)
		{
			if(_frigates.size() == 0)
				btnFrigate.setEnabled(false);
			if(_submarines.size() == 0)
				btnSubmarine.setEnabled(false);
			
			if(countFrigatesUsed >= _frigates.size())
				btnFrigate.setEnabled(false);
			
			if(countSubmarinesUsed >= _submarines.size())
				btnSubmarine.setEnabled(false);
		}
		else
		{
			if(_frigates.size() == 0)
				btnFrigate.setEnabled(false);
			if(_submarines.size() == 0)
				btnSubmarine.setEnabled(false);
			
			if(countFrigatesUsed >= _frigates.size())
				btnFrigate.setEnabled(false);
			
			if(countSubmarinesUsed >= _submarines.size())
				btnSubmarine.setEnabled(false);
		}
	}
	
	public static void Synchronize()
    {   	    	
    	//Clear the arrays
    	_frigates.clear();
    	_submarines.clear();
    	
    	//Set used vehicles
	    countFrigatesUsed = 0;
	    countSubmarinesUsed = 0; 
	    
		if(selectedTeamID >= 0 && selectedTeamID < 2)
		{
			for(int l = 0; l < Data.getVehiclesByTeam(Data.getAllTeams().get(selectedTeamID)).size(); l++)
			{
				if(Data.getVehiclesByTeam(Data.getAllTeams().get(selectedTeamID)).get(l).getVehicleType().toString().equals("FRIGATE"))
	      		 {
	      			 _frigates.add(Data.getVehiclesByTeam(Data.getAllTeams().get(selectedTeamID)).get(l));
	      		 }
	      		 else if(Data.getVehiclesByTeam(Data.getAllTeams().get(selectedTeamID)).get(l).getVehicleType().toString().equals("SUBMARINE"))
	      		 {
	      			_submarines.add(Data.getVehiclesByTeam(Data.getAllTeams().get(selectedTeamID)).get(l));
				 }
			}
			
			// Loop through the submarines and frigates to check if they are locked
			for(int k = 0; k < _frigates.size(); k++)
			{
				boolean locked = (boolean) _frigates.get(k).getLocked();
				if(locked)
				{
					countFrigatesUsed++;
				}
			}
			
			for(int k = 0; k < _submarines.size(); k++)
 			{
  				 boolean locked = (boolean) _submarines.get(k).getLocked();
  				 if(locked)
  				 {
  					 countSubmarinesUsed++;
  				 }
  			}
			updateButtons();
		}
    }
	
	public void run() 
    {
	    while(true){
    		try {
    			Thread.sleep(500);
    			if(selectedTeamID != 2)
    			{
    				Synchronize();
    			}
			} catch (InterruptedException e) {
				System.out.println(e.getMessage());
			}
		}
	}
}
